package push.tools.service.config.network.inter;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 失败重试
 */
public class RetryInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(RetryInterceptor.class);

    public int maxRetry = 3;//最大重试次数

    private int retryNum;//假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）


    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        logger.info("retryNum=" + retryNum);
        Response response = chain.proceed(request);

        while (!response.isSuccessful() && retryNum < maxRetry) {
            retryNum++;
            logger.info("retryNum=" + retryNum);
            response = chain.proceed(request);
        }
        return response;
    }
}
